﻿using Infrastructure.DbUtility;
using Infrastructure.Utility;
using System;
using System.Data;
using System.Linq;

public partial class admin_advertisement : BasePage
{
    protected Tuple<int, string>[] types = new Tuple<int, string>[] { 
        new Tuple<int,string>(0,"首页轮播广告")
    };

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Index = 1;
            this.LoadAdvertisements(1, string.Empty);
            if (Request["data"] == "list") this.GetAllAdvertisements();
        }
    }


    private void GetAllAdvertisements()
    {
        string sql = "SELECT * FROM Advertisment (NOLOCK) WHERE status = 1";
        DbHelper db = new DbHelper();
        var table = db.ExecQueryEx(sql);

        var arr = table.AsEnumerable().Select(r => string.Format("{{\"adid\":{0},\"adtitle\":\"{1}\",\"adurl\":\"{2}\"}}", r.Value("adid"), r.Value("adtitle"), r.Value("adurl")));

        Response.Clear();
        Response.Write("{\"success\": true,\"data\":[" + string.Join(",", arr) + "]}");
        Response.End();
    }

    private void LoadAdvertisements(int index, string keyword)
    {
        string sql = string.Empty;

        string filter = string.IsNullOrWhiteSpace(keyword) ? string.Empty : "[adtitle] LIKE  '%' + {0} + '%' OR [addescription] LIKE  '%' + {0} + '%'";

        sql = "SELECT COUNT(*) count FROM Advertisment (NOLOCK) " + (filter == string.Empty ? string.Empty : " WHERE " + filter) + Environment.NewLine;

        if (index == 1) sql += "SELECT TOP " + PAGE_SIZE + " * FROM Advertisment (NOLOCK)" + (filter == string.Empty ? string.Empty : " WHERE " + filter);
        else sql += "SELECT TOP " + PAGE_SIZE + " * FROM Advertisment (NOLOCK) WHERE adid NOT IN (SELECT TOP " + ((index - 1) * PAGE_SIZE) + " adid FROM Advertisment (NOLOCK))" + (filter == string.Empty ? string.Empty : " AND " + filter); ;

        DbHelper db = new DbHelper();
        var ds = db.ExecuteQueryEx(sql, keyword);

        this.Index = index;
        int count = ds.Tables[0].Rows[0].Value<int>("count");
        this.TotalSize = count / PAGE_SIZE + (count % PAGE_SIZE == 0 ? 0 : 1);

        lstAdvertisement.DataSource = ds.Tables[1].AsEnumerable().Select(r => new {
            adid = r.Value<int>("adid"),
            adtype = r.Value<int>("adtype"),
            adtypename = types.Where(t => t.Item1 == r.Value<int>("adtype")).Select(t => t.Item2).FirstOrDefault() ?? string.Empty,
            adimage = GetSitePath(r.Value("adimage")),
            adtitle = r.Value("adtitle"),
            addescription = r.Value("addescription"),
            adurl = r.Value("adurl"),
            adclicks = r.Value<int>("adclicks"),
            adstatus = r.Value<int>("adstatus"),
            creator = r.Value<int>("creator"),
            systime = r.Value<DateTime>("systime")
        });
        lstAdvertisement.DataBind();
    }
    protected void btnPost_Click(object sender, EventArgs e)
    {
        var keyword = txtName.Text.Trim();
        this.Index = 1;
        this.LoadAdvertisements(1, keyword);
    }
    protected void btnNavigate_Click(object sender, EventArgs e)
    {
        string sindex = Request["txtGoTo"];
        int index = 0;
        if (!int.TryParse(sindex, out index) || index < 1) return;

        var keyword = txtName.Text.Trim();
        this.Index = index;

        this.LoadAdvertisements(index, keyword);
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        var val = Request["selector"];
        if (string.IsNullOrWhiteSpace(val)) return;

        string sql = "DELETE FROM Advertisment WHERE adid IN (" + val + ")";

        DbHelper db = new DbHelper();
        db.ExecuteUpdate(sql);

        var keyword = txtName.Text.Trim();
        this.LoadAdvertisements(this.Index, keyword);
    }
    protected void btnSaveEdit_Click(object sender, EventArgs e)
    {
        var adid = 0;
        int.TryParse(Request["adid"], out  adid);
        var adtype = Request["adtype"];
        var adtitle = Request["adtitle"];
        var adurl = Request["adurl"];
        var addescription = Request["addescription"];
        var creator = 1;

        UploadHelper helper = new UploadHelper();
        DataRow fileRow = null;
        foreach (string k in Request.Files)
        {
            if (Request.Files[k] == null || Request.Files[k].InputStream == null || Request.Files[k].InputStream.Length == 0) continue;
            fileRow = helper.Upload(Request.Files[k], true);
            break;
        }

        string sql = string.Empty;
        if (adid <= 0) sql = "INSERT INTO Advertisment (adtype,adtitle,adimage,adurl,addescription,adclicks,creator) values ({0},{1},{2},{3},{4},0,{5})";
        else sql = "UPDATE  Advertisment SET adtype = {0}, adtitle = {1}, adimage = CASE WHEN ISNULL({2},'') = '' THEN adimage ELSE {2} END, adurl={3}, addescription = {4} where adid={5}";
        DbHelper db = new DbHelper();
        db.ExecuteUpdateEx(sql, adtype, adtitle, fileRow.Value("fullPath") ?? string.Empty, adurl, addescription, adid > 0 ? adid : creator);

        var keyword = txtName.Text.Trim();

        this.LoadAdvertisements(this.Index, keyword);
    }
}